package com.momin.gmall.product.exception;

import com.momin.common.utils.R;
import com.momin.exception.BizCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yyj
 * @Package com.momin.gmall.product.service
 * @date 2021/4/27 下午6:48
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.momin.gmall.product.controller")
public class ControllerExceptionAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R ValidException(MethodArgumentNotValidException e){
        log.error("数据校验异常,信息：{},类型：{}!",e.getMessage(),e.getClass());
        Map<String, String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach(item->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(value=Exception.class)
    public R handleException(Throwable throwable){
        log.error("数据异常:{},信息：{}",throwable.getMessage(),throwable.getClass());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
